package com.ytjj.qmyx.mall.api.h5.v1.score;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.mapper.OrdersDao;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.dto.SignDto;
import com.ytjj.qmyx.mall.model.response.H5ScorePageResponse;
import com.ytjj.qmyx.mall.model.response.H5SignResponse;
import com.ytjj.qmyx.mall.model.response.ProductShortResponse;
import com.ytjj.qmyx.mall.model.response.UserCenterResponse;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.CommonService;
import com.ytjj.qmyx.mall.utils.DateUtils;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;


/**
 * 积分控制器
 *
 *
 * @version 1.0
 * 
 */
@RestController
@RequestMapping("/v1/score")
@Slf4j
public class ScoreController extends BaseController {

    private final ActivityService activityService;

    private final CommonService commonService;

    private final UsersClient usersClient;
    @Resource
    private RedisService redisService;
    @Autowired
    private SysConfigUtil sysConfigUtil;

    @Resource
    private OrdersDao ordersDao;

    public ScoreController(ActivityService activityService, CommonService commonService, UsersClient usersClient) {
        this.activityService = activityService;
        this.commonService = commonService;
        this.usersClient = usersClient;
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @GetMapping("/getH5ScoreListByType")
    public CommonResult getH5ScoreListByType(@RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
//        UsersResponse user = this.getH5CurrentUser();
        H5ScorePageResponse h5ScorePageResponse = null;
        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_H5_" + flag;
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            h5ScorePageResponse = JSONObject.parseObject(s, H5ScorePageResponse.class);
        } else {
            h5ScorePageResponse = activityService.getH5ScoreListByType(flag);
            redisService.set(key, JSONObject.toJSONString(h5ScorePageResponse));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        // 最新未支付的订单
        List<Orders> ordersList = ordersDao.queryNewUsersOrderIdH5(TokenUtil.getToken());
        if (!CollectionUtils.isEmpty(ordersList)) {
            h5ScorePageResponse.setOrderId(ordersList.get(0).getId());
        }
        // 签到
        H5SignResponse h5SignResponse = new H5SignResponse();
        // 默认积分
        h5SignResponse.setExclusiveScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        // 是否签到
        String signStr = redisService.get(RedisConstants.H5_SIGN +
                Optional.ofNullable(TokenUtil.getToken()).orElse("xxx"));
        if (signStr != null) {
            SignDto signDto = JSONObject.parseObject(signStr, SignDto.class);
            try {
                int isYeaterday = DateUtils.isYeaterday(signDto.getSignTime(), new Date());
                if (isYeaterday == -1) {
                    h5SignResponse.setIsSign(1);
                } else if (isYeaterday == 1) {
                    h5SignResponse.setIsSign(0);
                } else {
                    h5SignResponse.setIsSign(0);
                    redisService.remove(RedisConstants.H5_SIGN + TokenUtil.getToken());
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            h5SignResponse.setIsSign(0);
        }
        h5SignResponse.setTomorrowScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.H5_SIGN_SCORE)));
        Map<String, Object> result = new HashMap<>();
        result.put("h5ScorePageResponse", h5ScorePageResponse);
        result.put("h5SignResponse", h5SignResponse);
        return CommonResult.success(result);
    }

    /**
     * 用户中心积分商品
     *
     * @return
     */
    @GetMapping("/getUserCenterData")
    public CommonResult getUserCenterData() {
        UserCenterResponse result = activityService.getUserCenterData();
        return CommonResult.success(result);
    }

    /**
     * 查询积分栏目集合
     */
    @GetMapping("/queryCashScoreColumnH5")
    public CommonResult queryCashScoreColumnH5() {
        Map<String,Object> result = activityService.queryCashScoreColumnH5();
        result.put("score",this.getH5CurrentUser().getScore());
        return CommonResult.success(result);
    }

    /**
     * 根据积分栏目查询上铺列表
     */
    @GetMapping("/queryCashScoreListH5")
    public CommonResult queryCashScoreListH5(@RequestParam(value = "columnId", required = false) Integer columnId,
                                             @RequestParam(value = "pageSize") Integer pageSize,
                                             @RequestParam(value = "pageNum") Integer pageNum,
                                             @RequestParam(value = "flag", required = false) Integer flag,
                                             @RequestParam(value = "consumerPower",defaultValue = "",required = false) String consumerPower) {
        List<ProductShortResponse> result = activityService.queryCashScoreListH5(columnId,pageSize,pageNum,flag,consumerPower, null);
        return CommonResult.success(result);
    }

}
